package com.senlingspace.web.controller.weixin.delivery;

import cn.hutool.core.io.unit.DataUnit;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.senlingspace.common.core.domain.AjaxResult;
import com.senlingspace.common.enums.OrderSource;
import com.senlingspace.common.enums.OrderType;
import com.senlingspace.common.utils.DateUtils;
import com.senlingspace.common.utils.StringUtils;
import com.senlingspace.common.utils.http.HttpJsonUtils;
import com.senlingspace.common.utils.http.HttpUtils;
import com.senlingspace.system.domain.*;
import com.senlingspace.system.domain.query.weixin.delivery.addorder.*;
import com.senlingspace.system.domain.query.weixin.delivery.wechatToken.WechatTokenParam;
import com.senlingspace.system.domain.query.weixin.sendGoods.*;
import com.senlingspace.system.mapper.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.OrderUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PreDestroy;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 微信物流 controller
 *
 * @author wangliang
 */

@Slf4j
@Validated
@AllArgsConstructor
@RestController
@RequestMapping(path = "/wmp/delivery/v1")
public class LogisticsController {

    @Autowired
    private SlkjOrderMapper orderMapper;

    @Autowired
    private SlkjCustomerMapper customerMapper;

    @Autowired
    private SlkjShopMapper shopMapper;

    @Autowired
    private SlkjOrderPricingSnapshotMapper slkjOrderPricingSnapshotMapper;

    @Autowired
    private SlkjProductMapper goodsMapper;

    /**
     *
     * 获取微信token
     * @author wangliang
     * @return com.alibaba.fastjson2.JSONObject
     */
    @PostMapping("/getWechatToken")
    public JSONObject getWechatToken() {
        WechatTokenParam wechatTokenParam = new WechatTokenParam();
        wechatTokenParam.setAppid("wx31d27927330d3f9f");
        wechatTokenParam.setGrant_type("client_credential");
        wechatTokenParam.setSecret("e69c6e464f542d48eecb432c9f9799a1");
        wechatTokenParam.setForce_refresh(false);
        String token = HttpJsonUtils.sendJsonPost("https://api.weixin.qq.com/cgi-bin/stable_token", JSON.toJSONString(wechatTokenParam));
        JSONObject jsonToken = JSONObject.parseObject(token);
        return jsonToken;
    }


    /**
     *
     * 生产运单
     * @author wangliang
     * @param orderId
     * @return com.alibaba.fastjson2.JSONObject
     */
    public void generateWaybill(Long orderId) {
        JSONObject wechatToken = getWechatToken();
        String accessToken = wechatToken.get("access_token").toString();
        AddDeliveryOrder addDeliveryOrder = new AddDeliveryOrder();
        /** 获取订单中的用户信息ID **/
        SlkjOrder order = orderMapper.selectSlkjOrderByOrderId(orderId);
        /** 小程序订单 并且为商品订单 获取用户的收货地址**/
        JSONObject jsonToken = new JSONObject();
        if (OrderSource.MINI_PROGRAM.getCode() == order.getSource() && OrderType.OT_102.getCode() == order.getOrderType() && StringUtils.isNotNull(order.getAddressSnapshot())) {
            jsonToken = JSON.parseObject(order.getAddressSnapshot());
        }
        Long customerId = order.getCustomerId();
        /** 门店Id **/
        Long shopId = order.getShopId();
        /** 根据用户信息ID获取用的openid **/
        SlkjCustomer customer = customerMapper.getCustomerByCustomerId(customerId);

        if (customer == null) {
            throw new IllegalArgumentException("获取用户信息异常");
        }

        addDeliveryOrder.setOrder_id(orderId.toString());
        addDeliveryOrder.setOpenid(customer.getOpenId());
        addDeliveryOrder.setDelivery_id("SF");
        addDeliveryOrder.setBiz_id("SF_CASH");
        addDeliveryOrder.setCustom_remark("易碎物品");
        addDeliveryOrder.setAdd_source(0);
        SlkjShop slkjShop = shopMapper.selectSlkjShopByShopId(shopId);
        /** 发货人信息 **/
        AddSender addSender = new AddSender();
        addSender.setName(slkjShop.getContactPerson());
        addSender.setMobile(slkjShop.getContactTel());
        addSender.setCompany(slkjShop.getShopName());
        addSender.setCountry("中国");
        addSender.setProvince(slkjShop.getProvinceName());
        addSender.setCity(slkjShop.getCityName());
        addSender.setArea(slkjShop.getCountyName());
        addSender.setAddress(slkjShop.getAddress());
        addDeliveryOrder.setSender(addSender);
        /** 收货人信息 **/
        AddReceiver receiver = new AddReceiver();
        receiver.setName(jsonToken.get("receiverName").toString());
        String receiverPhone = jsonToken.get("receiverPhone").toString();
        receiver.setMobile(receiverPhone);
        receiver.setCountry("中国");
        receiver.setProvince(jsonToken.get("provinceName").toString());
        receiver.setCity(jsonToken.get("cityName").toString());
        receiver.setArea(jsonToken.get("countyName").toString());
        receiver.setAddress(jsonToken.get("detailAddress").toString());
        addDeliveryOrder.setReceiver(receiver);

        /** 包裹信息，将传递给快递公司 **/
        AddCargo addCargo = new AddCargo();
        addCargo.setCount(1);
        addCargo.setWeight(1.0);
        addCargo.setSpace_x(1.0);
        addCargo.setSpace_y(1.0);
        addCargo.setSpace_z(1.0);
        /** 查询商品名称和购买数量 **/
        Integer addShopGoodsCount = 0;
        List<SlkjOrderPricingSnapshot> slkjOrderPricingSnapshots = slkjOrderPricingSnapshotMapper.selectByOrderId(orderId);
        ArrayList<AddCargoDetail> addCargoDetails = new ArrayList<>();
        for (SlkjOrderPricingSnapshot snapshot : slkjOrderPricingSnapshots) {
            AddCargoDetail addCargoDetail = new AddCargoDetail();
            addCargoDetail.setCount(snapshot.getQuantity());
            addCargoDetail.setName(snapshot.getGoodsName());
            addCargoDetails.add(addCargoDetail);
            addShopGoodsCount = addShopGoodsCount + snapshot.getQuantity();
        }
        addCargo.setDetail_list(addCargoDetails);
        addDeliveryOrder.setCargo(addCargo);

        /** 商品信息，会展示到物流服务通知和电子面单中 **/
        AddShop addShop = new AddShop();
        addShop.setGoods_count(addShopGoodsCount);
        SlkjProduct product = goodsMapper.selectSlkjProductByProductId(slkjOrderPricingSnapshots.get(0).getGoodsId());
        addShop.setImg_url(product.getProductImg());
        addShop.setGoods_name(slkjOrderPricingSnapshots.get(0).getGoodsName());

        addDeliveryOrder.setShop(addShop);

        /** 保价信息 **/
        AddInsured addInsured = new AddInsured();
        addInsured.setInsured_value(0);
        addInsured.setUse_insured(0);
        addDeliveryOrder.setInsured(addInsured);

        AddMerchant addMerchant = new AddMerchant();
        addMerchant.setService_type(0);
        addMerchant.setService_name("标准快递");
        addDeliveryOrder.setService(addMerchant);
        addDeliveryOrder.setSetExpect_time(System.currentTimeMillis());
        String httpUrl = "https://api.weixin.qq.com/cgi-bin/express/business/order/add?access_token=";
        String token = HttpJsonUtils.sendJsonPost(httpUrl + accessToken, JSON.toJSONString(addDeliveryOrder));

        log.info("请求参数：{}," + JSON.toJSONString(addDeliveryOrder));
        JSONObject data = JSONObject.parseObject(token);
        /** 顺丰运单单号 **/
        Object waybillId = data.get("waybill_id");
        /** 将订单号更新到数据库中 **/
        order.setExpressNumber(waybillId.toString());
        orderMapper.updateSlkjOrder(order);

    }


    @PostMapping("/addOrder")
    public JSONObject logisticsType(Long orderId){
        SlkjOrder order = orderMapper.selectSlkjOrderByOrderId(orderId);
        // 小程序订单商品订单，并需要邮寄
        if (OrderSource.MINI_PROGRAM.getCode() == order.getSource() && OrderType.OT_102.getCode() == order.getOrderType() && StringUtils.isNotNull(order.getAddressSnapshot())) {
            generateWaybill(orderId);
            return uploadShippingInfo(order,1);
        }else if(OrderSource.MINI_PROGRAM.getCode() == order.getSource() && OrderType.OT_102.getCode() == order.getOrderType() && StringUtils.isNull(order.getAddressSnapshot())){
            //小程序商品订单，需上门自提 发货快递类型为4
           return uploadShippingInfo(order,4);

        }else if(OrderSource.MINI_PROGRAM.getCode() == order.getSource() && OrderType.OT_101.getCode() == order.getOrderType()){
            //小程序购票   虚拟物品快递类型为3
           return uploadShippingInfo(order,3);
        }else {
            log.info("订单ID，{}" + orderId);
            throw new IllegalArgumentException("订单类型有误，请核对订单信息");
        }
    }



    /**
     *
     * 发货信息录入
     * @author wangliang
     * @param order
     * @param logisticsType 1、实体物流配送采用快递公司进行实体物流配送形式 2、同城配送 3、虚拟商品，虚拟商品，例如话费充值，点卡等，无实体配送形式 4、用户自提
     * @return com.alibaba.fastjson2.JSONObject
     */
    public JSONObject uploadShippingInfo(SlkjOrder order,int logisticsType){
        JSONObject wechatToken = getWechatToken();
        String accessToken = wechatToken.get("access_token").toString();
        SendGoodsDto sendGoodsDto = new SendGoodsDto();

        // 订单，需要上传物流信息的订单
        OrderKey orderKey = new OrderKey();
        orderKey.setOrderNumberType(2);
        orderKey.setTransactionId(order.getAccTradeNo());
        sendGoodsDto.setOrderKey(orderKey);

        sendGoodsDto.setLogisticsType(logisticsType);
        sendGoodsDto.setDeliveryMode("UNIFIED_DELIVERY");
        sendGoodsDto.setAllDelivered(true);


        List<SlkjOrderPricingSnapshot> slkjOrderPricingSnapshots = slkjOrderPricingSnapshotMapper.selectByOrderId(order.getOrderId());
        ArrayList<ShippingList> list = new ArrayList<>();
        // 物流信息列表
        ShippingList shippingList = new ShippingList();
        shippingList.setTrackingNo(order.getExpressNumber());
        shippingList.setExpressCompany("SF");
        if(logisticsType == 3){
            shippingList.setItemDesc(slkjOrderPricingSnapshots.get(0).getTicketCategoryName());
        }else {
            shippingList.setItemDesc(slkjOrderPricingSnapshots.get(0).getGoodsName());
        }
        list.add(shippingList);
        sendGoodsDto.setShippingList(list);

        sendGoodsDto.setUploadTime(DateUtils.getFormDate());
        SlkjCustomer customer = customerMapper.getCustomerByCustomerId(order.getCustomerId());

        if (customer == null) {
            throw new IllegalArgumentException("获取用户信息异常");
        }
        Payer payer = new Payer();
        payer.setOpenid(customer.getOpenId());
        sendGoodsDto.setPayer(payer);

        String httpUrl = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=";
        String token = HttpJsonUtils.sendJsonPost(httpUrl + accessToken, JSON.toJSONString(sendGoodsDto));

        log.info("请求参数：{}," + JSON.toJSONString(sendGoodsDto));
        JSONObject data = JSONObject.parseObject(token);
        return data;

    }



}

